// main.go
package main

import (
	"log"

	"URLshortener/config"
	"URLshortener/internal/controller"
	"URLshortener/internal/dao/cache"
	"URLshortener/internal/dao/sql"
	"URLshortener/internal/model"
	"URLshortener/internal/routes"
	"URLshortener/internal/service"
	"URLshortener/pkg/database"
	"github.com/gin-gonic/gin"
)

func main() {
	// 加载配置
	cfg := config.LoadConfig()

	// 初始化数据库
	engine, err := database.NewMysqlEngine(cfg.DatabaseDSN)
	if err != nil {
		log.Fatalf("数据库初始化失败: %v", err)
	}
	// 创建表结构
	if err := model.InitTable(engine); err != nil {
		log.Fatalf("表结构初始化失败: %v", err)
	}

	// 初始化redis
	redisCache := cache.NewRedisCache(cfg.RedisAddr, cfg.RedisPassword, cfg.RedisDB)

	// 构建依赖
	// 依赖链：Main → Config → Database → DAO → Service → Controller
	// controller → service → dao → database
	urlDao := sql.NewUrlDao(engine)
	urlService := service.NewUrlService(urlDao, redisCache)
	urlCtrl := controller.NewUrlController(urlService)

	// 初始化Gin
	router := gin.Default()

	// 注册路由
	routes.RegisterRoutes(router, urlCtrl)

	// 启动服务
	log.Println("服务启动在 :8080")
	router.Run(":8080")
}
